package com.tus.task;

import com.tus.model.UploadInfo;
import com.tus.store.MetadataStore;
import com.tus.storage.FileStorage;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExpiredUploadCleaner {
    private final MetadataStore metadataStore;
    private final FileStorage fileStorage;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public ExpiredUploadCleaner(MetadataStore metadataStore, FileStorage fileStorage) {
        this.metadataStore = metadataStore;
        this.fileStorage = fileStorage;
    }

    public void start() {
        scheduler.scheduleAtFixedRate(() -> {
            System.out.println("[Cleaner] Running expired upload cleanup...");
            long now = System.currentTimeMillis();
            List<UploadInfo> expired = metadataStore.findExpired(now);
            for (UploadInfo info : expired) {
                try {
                    fileStorage.deleteFile(info.getFilePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                metadataStore.deleteUpload(info.getUploadId());
                System.out.println("[Cleaner] Deleted expired upload: " + info.getUploadId());
            }
        }, 1, 1, TimeUnit.HOURS); // 每小时检查一次
    }

    public void shutdown() {
        scheduler.shutdown();
    }
}